package com.dream.classinfo;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.dream.bean.ClassBean;
import com.dream.bean.ClassInfoBean;
import com.example.wzsdk.attention.Equipment;
import com.example.wzsdk.login.Landing;
import com.example.wzsdk.login.LoginState;
import com.google.gson.Gson;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity implements View.OnClickListener {

    //WEB请求URL，ip和id通过sharedPreferences获取
    private static final String URL="/Services/AndroidService.svc/Android/GetNoticeToAndroids/";

    private TextView tv_college;
    private TextView tv_className;
    private TextView tv_classIndex;
    private TextView tv_sysTime;
    private TextView tv_sysDate;
    private TextView tv_wendu;
    private TextView tv_shidu;
    private TextView tv_theCourseStr;
    private TextView tv_theCourse;
    private TextView tv_courseTimeStr;
    private TextView tv_courseTime;
    private TextView tv_courseTeacherStr;
    private TextView tv_courseTeacher;
    private TextView tv_notifTheme;
    private TextView tv_notifContent;
    private Typeface typeface1,typeface2;
    private List<ClassBean> gradeLists;
    private List<ClassBean> notifLists;
    private Gson gson;
    private ClassInfoBean classInfoBean;
    //设置界面进入计数器
    private int logCount=0;
    //通知索引
    private int notifIndex=0;
    private SimpleDateFormat sdf;
    private TextView courseDate;
    private Message message;
    private SharedPreferences sharedPreferences;
    private Timer getDatatimer,sysTimetimer,notiytimer;
    private SDKManager sdkManager;

    private static final int MSG=0;
    private static final int SET_DATA=1;
    private static final int SYSTIME=2;
    private static final int LOOP_NOTIF=3;
    private static final int WEIZONE_SET_VAL=4;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG:
                    Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                    break;
                case SET_DATA:
                    setDataToUI();
                    break;
                case SYSTIME:
                    tv_sysDate.setText(fomatDate()[0]);
                    tv_sysTime.setText(fomatDate()[1]);
                    break;
                case LOOP_NOTIF:
                    nextNotif();
                    break;
                case WEIZONE_SET_VAL:
                    setWenShi((String[]) msg.obj);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
        initTimer();
        initSDK();
    }

    public void initSDK(){
        sdkManager=new SDKManager(this);
        sdkManager.initLanding();
        if (sdkManager.getWeizonIp()!=null&&!sdkManager.getWeizonIp().equals("")){
            sdkManager.setSdkDataListener(new SDKManager.onGetData() {
                @Override
                public void onSearchFinish(String weiZoneIp) {

                }

                @Override
                public void getLandState(boolean isLand) {
                    if (isLand){sdkManager.attentionVariable("30008");}
                }
                @Override
                public void getDevData(String UIID, String VALUE, String RFID, String INDEX, String DEVID, String HOST) {
                    System.out.println("UIID："+UIID+" VALUE："+VALUE+" RFID："+RFID+" INDEX："+INDEX+" DEVID: "+DEVID+" HOST："+HOST);
                    if (UIID.equals("30008")){
                        Message message=new Message();
                        message.what=WEIZONE_SET_VAL;
                        message.obj=new String[]{UIID,VALUE,RFID,INDEX,DEVID,HOST};
                        handler.sendMessage(message);
                    }
                }
            });
            sdkManager.landingSDK();
        }
    }

    public void setWenShi(String[] sdkInfoArr){
        if (sdkInfoArr[3].equals("1")){
            tv_wendu.setText(sdkInfoArr[1]+"℃");
        }
        if (sdkInfoArr[3].equals("2")){
            tv_shidu.setText(sdkInfoArr[1]+"%");
        }
    }

    public void initTimer(){
        //请求服务器数据
        getDatatimer=new Timer();
        getDatatimer.schedule(new TimerTask() {
            @Override
            public void run() {
                getdata();
            }
        },0,sharedPreferences.getInt("httpRequestTime",60000));
        //更新系统时间
        sysTimetimer=new Timer();
        sysTimetimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(SYSTIME);
            }
        },0,1000);
        //通知内容轮播
        notiytimer=new Timer();
        notiytimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (classInfoBean!=null&&classInfoBean.isSuccess()){
                    handler.sendEmptyMessage(LOOP_NOTIF);
                }
            }
        },10000,sharedPreferences.getInt("notifTime",60000));
    }

    //初始化控件
    public void initView(){
        //加载字体
        try {
            typeface1 = Typeface.createFromAsset(getAssets(), "FZLTHK.TTF");
            typeface2 = Typeface.createFromAsset(getAssets(), "FZLTXHK.TTF");
        } catch (Exception e) {
            typeface1=null;
            typeface2=null;
            Toast.makeText(this,"字体加载失败",Toast.LENGTH_SHORT).show();
        }
        gson=new Gson();
        sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sharedPreferences=getSharedPreferences("appinfo",MODE_PRIVATE);
        tv_college = (TextView) findViewById(R.id.college);
        tv_className = (TextView) findViewById(R.id.className);
        tv_classIndex = (TextView) findViewById(R.id.classIndex);
        tv_sysTime = (TextView) findViewById(R.id.sysTime);
        tv_sysTime.getPaint().setFakeBoldText(true);
        tv_sysDate = (TextView) findViewById(R.id.sysDate);
        tv_sysDate.getPaint().setFakeBoldText(true);
        tv_wendu = (TextView) findViewById(R.id.wendu);
        tv_wendu.getPaint().setFakeBoldText(true);
        tv_shidu = (TextView) findViewById(R.id.shidu);
        tv_shidu.getPaint().setFakeBoldText(true);
        tv_theCourseStr = (TextView) findViewById(R.id.the_course_str);
        tv_theCourse = (TextView) findViewById(R.id.the_course);
        tv_courseTimeStr = (TextView) findViewById(R.id.course_time_str);
        tv_courseTime = (TextView) findViewById(R.id.course_time);
        courseDate = (TextView) findViewById(R.id.course_date);
        tv_courseTeacherStr = (TextView) findViewById(R.id.course_teacher_str);
        tv_courseTeacher = (TextView) findViewById(R.id.course_teacher);
        tv_notifTheme = (TextView) findViewById(R.id.notif_theme);
        tv_notifContent = (TextView) findViewById(R.id.notif_content);
        tv_classIndex.setText(sharedPreferences.getString("className","1001室"));
        if (typeface1!=null){
            tv_college.setTypeface(typeface1);
            tv_className.setTypeface(typeface1);
            tv_classIndex.setTypeface(typeface1);
            tv_sysTime.setTypeface(typeface1);
            tv_sysDate.setTypeface(typeface1);
            tv_wendu.setTypeface(typeface1);
            tv_shidu.setTypeface(typeface1);
            tv_theCourse.setTypeface(typeface1);
            tv_courseTime.setTypeface(typeface1);
            tv_courseTeacher.setTypeface(typeface1);
            tv_notifTheme.setTypeface(typeface1);
        }
        if (typeface2!=null){
            tv_theCourseStr.setTypeface(typeface2);
            tv_courseTimeStr.setTypeface(typeface2);
            courseDate.setTypeface(typeface2);
            tv_courseTeacherStr.setTypeface(typeface2);
            tv_notifContent.setTypeface(typeface2);
        }
    }

    //更新数据
    public void setDataToUI(){
        Toast.makeText(MainActivity.this,"更新成功",Toast.LENGTH_SHORT).show();
        if (notifLists!=null&&notifLists.size()>0){
            setNotifData(notifLists.get(notifIndex));
        }else {
            tv_notifTheme.setText("暂无信息");
            tv_notifContent.setGravity(Gravity.CENTER);
            tv_notifContent.setText("暂无信息");
            notifIndex=0;
        }
        if (gradeLists!=null&&gradeLists.size()>0){
            try {
                Date date = sdf.parse(sdf.format(System.currentTimeMillis()));
                for (int i = 0; i < gradeLists.size(); i++) {
                    int start_num = sdf.parse(gradeLists.get(i).getStartTime()).compareTo(date);
                    int end_num = sdf.parse(gradeLists.get(i).getEndTime()).compareTo(date);
                    if (start_num<=0&&end_num>=0){
                        Date date2 = sdf.parse(sdf.format(System.currentTimeMillis() + (sharedPreferences.getInt("gradeNexrTime",30) * 1000 * 60)));
                        if (sdf.parse(gradeLists.get(i).getEndTime()).compareTo(date2)>=0){
                            //tv_theCourseStr.setText("当前课程");
                            tv_theCourseStr.setText("");
                            setGradeData(gradeLists.get(i));
                            break;
                        }else if ((i+1)<=gradeLists.size()-1){
                            //tv_theCourseStr.setText("最近课程");
                            tv_theCourseStr.setText("");
                            setGradeData(gradeLists.get(i+1));
                            break;
                        }else {
                            //tv_theCourseStr.setText("当前课程");
                            tv_theCourseStr.setText("");
                            setGradeData(gradeLists.get(i));
                            break;
                        }
                    }else if (start_num>0){
                        //tv_theCourseStr.setText("最近课程");
                        tv_theCourseStr.setText("");
                        setGradeData(gradeLists.get(i));
                        break;
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            tv_theCourse.setText("暂无信息");
            tv_courseTime.setText("暂无信息");
            courseDate.setText("暂无信息");
            tv_courseTeacher.setText("暂无信息");
            tv_className.setText("暂无班级");
        }
    }

    //通知控件赋值
    public void setNotifData(ClassBean classBean){
        tv_notifTheme.setText(classBean.getNotifyTheme());
        tv_notifContent.setGravity(Gravity.CENTER);
        tv_notifContent.setText(classBean.getNotifyText());
    }

    //课程控件赋值
    public void setGradeData(ClassBean classBean){
        tv_theCourse.setText(classBean.getCourseInfoName());
        tv_courseTime.setText(classBean.getStartTime().split(" ")[1]+" - "+classBean.getEndTime().split(" ")[1]);
        courseDate.setText(classBean.getStartTime().split(" ")[0]);
        tv_courseTeacher.setText(classBean.getSubmitUserName());
        tv_className.setText(classBean.getClassName()+"班");
    }

    //请求服务器获取数据
    public void getdata(){
        if (!sharedPreferences.getString("ip","").equals("")){
            new HttpData(MainActivity.this,"http://"+sharedPreferences.getString("ip","")+URL+sharedPreferences.getString("id","")).getResponse(new HttpData.getResult() {
                @Override
                public void onSuccess(String result) {
                    classInfoBean = gson.fromJson(result, ClassInfoBean.class);
                    if (classInfoBean.isSuccess()){
                        if (gradeLists==null){
                            gradeLists=new ArrayList<ClassBean>();
                        }
                        if (notifLists==null){
                            notifLists=new ArrayList<ClassBean>();
                        }
                        gradeLists.clear();
                        notifLists.clear();
                        for (int i = 0; i < classInfoBean.getData().size(); i++) {
                            ClassBean classbean=classInfoBean.getData().get(i);
                            if (classbean.getMessageType()==0){
                                notifLists.add(classbean);
                            }else if (classbean.getMessageType()==1){
                                gradeLists.add(classbean);
                            }
                        }
                        rankList(notifLists);
                        rankList(gradeLists);
                        handler.sendEmptyMessage(SET_DATA);
                    }else {
                        message=new Message();
                        message.what=MSG;
                        message.obj=classInfoBean.getMsg();
                        handler.sendMessage(message);
                        tv_theCourse.setText("暂无信息");
                        tv_courseTime.setText("暂无信息");
                        courseDate.setText("暂无信息");
                        tv_courseTeacher.setText("暂无信息");
                        tv_className.setText("暂无班级");
                        tv_notifTheme.setText("暂无信息");
                        tv_notifContent.setText("暂无信息");
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //点击5次log打开设置界面
            case R.id.college:
                logCount++;
                if (logCount==5){
                    logCount=0;
                    startActivity(new Intent(MainActivity.this,SettingActivity.class));
                    finish();
                }
                break;
        }
    }
    //切换下一条通知
    public void nextNotif(){
        if (notifLists!=null&&notifLists.size()>0){
            if (notifIndex==notifLists.size()-1){
                notifIndex=0;
            }else {
                notifIndex++;
            }
            setNotifData(notifLists.get(notifIndex));
        }
    }

    //切换上一条通知
    public void lastNotif(){
        if (notifLists!=null&&notifLists.size()>0){
            if (notifIndex==0){
                notifIndex=notifLists.size()-1;
            }else {
                notifIndex--;
            }
            setNotifData(notifLists.get(notifIndex));
        }
    }

    //格式化系统时间
    public String[] fomatDate(){
        SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日 HH:mm");
        return sdf.format(new Date()).split(" ");
    };

    //List集合排序
    public void rankList(List<ClassBean> list){
        Collections.sort(list, new Comparator<ClassBean>() {
            @Override
            public int compare(ClassBean o1, ClassBean o2) {
                try {
                    Date date1 = sdf.parse(o1.getStartTime());
                    Date date2 = sdf.parse(o2.getStartTime());
                    return date1.compareTo(date2);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return 0;
            };
        });
    }

    //发送消息
    public void senToast(String error){
        message=new Message();
        message.what=MSG;
        message.obj=error;
        handler.sendMessage(message);
    }

    @Override
    protected void onDestroy() {
        sdkManager.exit();
        if (getDatatimer!=null){
            getDatatimer.cancel();
        }
        if (sysTimetimer!=null){
            sysTimetimer.cancel();
        }
        if (notiytimer!=null){
            notiytimer.cancel();
        }
        super.onDestroy();
    }


}
